package com.jnc.common.util.convert;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

@Slf4j
public final class SerializeUtil {
	/**
	 * deserialize
	 * 注意：此处的bytes数组，一定要ObjectOutputStream序列化而来的byte数组，不然会报错
	 * @param bytes
	 * @return
	 */
	public static Object deserialize(byte[] bytes) {
		Object result = null;
		if (isEmpty(bytes)) {
			return null;
		}
		try {
			ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
			try {
				ObjectInputStream objectInputStream = new ObjectInputStream(new BufferedInputStream(byteStream));
				try {
					result = objectInputStream.readObject();
				} catch (ClassNotFoundException ex) {
					log.error("Failed to deserialize object type Exception: {}", ex);
				}
			} catch (Throwable ex) {
				log.error("Failed to deserialize Exception: {}", ex);
			}
		} catch (Exception e) {
			log.error("Failed to deserialize Exception: {}", e);
		}
		return result;
	}

	public static boolean isEmpty(byte[] data) {
		return data == null || data.length == 0;
	}

	/**
	 * serialize
	 * 
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object) {
		byte[] result = null;
		if (object == null) {
			return new byte[0];
		}
		try {
			ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
			try {
				if (!(object instanceof Serializable)) {
					log.error("{} requires a Serializable payload, but received an object of type [ {} ]", SerializeUtil.class.getSimpleName(), object.getClass().getName());
					return null;
				}
				ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(byteStream));
				objectOutputStream.writeObject(object);
				objectOutputStream.flush();
				result = byteStream.toByteArray();
			} catch (Throwable ex) {
				log.error("Failed to serialize Exception: {}", ex);
			}
		} catch (Exception ex) {
			log.error("Failed to serialize Exception: {}", ex);
		}
		return result;
	}

}
